package rabbitMQConnection;

import com.rabbitmq.client.Connection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.channels.Channel;

/**
 * 发送类,外边可调用其中的发送方法
 *
 * @Author:CJJ
 * @Date:2025/5/10
 */
@Component
public class RabbitMQSender {
    @Autowired
    private RabbitMQConnectionPool connectionPool;


    private final int MaxRetries = 5;//最大重试次数

    public boolean sendMessage(String queueName, String message) {
        return sendMessage(queueName, message);
    }

    /**
     * category:业务类型
     * 发送时如果连接失败,自动重连,直至成功活重连次数超标
     */
    public boolean sendMessage(String queueName, String message, String category) throws InterruptedException {
        boolean ok = true;
        int attempt = 0;
        while (attempt < MaxRetries) {
            Connection connection = null;
            Channel channel = null;
            try {
                connection = (Connection) connectionPool.getConnection();
                if (connection == null) {
                    System.out.println("获取连接失败,正在重试...");
                    attempt++;
                    Thread.sleep(1000);//等待一段时间后重试
                    continue;
                }

                System.out.println(String.format("[%s] Sent to '%s',length:%d", queueName, message, category));
                break;//发送成功后退出循环
            } catch (Exception e) {
                attempt++;
                System.out.println("An error occurred,retrying...");
                e.printStackTrace();
            } finally {
                //确保通道和连接在这这里被关闭
                try {
                    if (channel != null) {
                        channel.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (connection != null) {
                    //返回连接到连接池,而不是关闭它
                    connectionPool.returnConnection((com.rabbitmq.client.Connection) connection);
                }
            }
        }
        if (attempt == MaxRetries) {
            ok = false;
            System.out.println("Failed to send message after" + MaxRetries + "attempts");
        }
        return ok;
    }
}
